'use strict'
let products=[
    {
        id:1,
        productName:'小米6x',
        price:5600,
        stockNum:500,
        supplire:'雷军'
    },
    {
        id:2,
        productName:'小米6x',
        price:5600,
        stockNum:500,
        supplire:'雷军'
    },
    {
        id:3,
        productName:'小米6x',
        price:5600,
        stockNum:500,
        supplire:'雷军'
    },
    {
        id:4,
        productName:'小米6x',
        price:5600,
        stockNum:500,
        supplire:'雷军'
    },
]

let fn_list=(ctx,next)=>{
    let keyword=ctx.request.query.keyword || ''
    if(keyword){
        let arr=products.filter(item=>{
            return item.id==keyword||item.productName==keyword||item.price==keyword||item.stockNum==keyword||item.supplire==keyword
        })
        ctx.body={
            code:1000,
            data:arr,
            msg:'请求成功'
        }
    }else{
        ctx.body={
            codea:1000,
            data:products,
            msg:'请求成功'
        }
    }
}

let fn_getById=(ctx,next)=>{
    let id=ctx.request.params.id
    let filterList=products.filter(item=>{
       return item.id==id
    })
    if(filterList.length>0){
        ctx.body={
            code:1000,
            data:filterList[0],
            msg:'获取成功'
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'获取指定元素失败'
        }
    }
}

let fn_post=(ctx,next)=>{
    let obj=ctx.request.body
    obj.id=products[products.length-1].id+1
    products.push(obj)
    ctx.body=obj
}

let fn_put=(ctx,next)=>{
    let id=ctx.request.params.id
    let obj=ctx.request.body
    let filterList=products.filter(item=>{
        return item.id==id
    })

    if(filterList.length>0){
        let tmpObj=filterList[0]
        tmpObj.productName=obj.productName
        tmpObj.price=obj.price
        tmpObj.stockNum=obj.stockNum
        tmpObj.supplire=obj.supplire
        ctx.body={
            code:1000,
            data:tmpObj,
            msg:'修改成功'
        }
    }else{
        ctx.body={
            code:400,
            data:'',
            msg:'元素不存在'
        }
    }
}

let fn_delete=(ctx,next)=>{
    let id=ctx.request.params.id
    let arr=products.filter(item=>{
        return item.id != id
    })
    if(arr.length<products.length){
        products=arr
        ctx.body={
            code:1000,
            data:{id},
            msg:'删除成功'
        }
    }else{
        ctx.body={
            code:400,
            data:null,
            msg:'元素不存在'
        }
    }
}

module.exports={
    'get /product':fn_list,
    'get /product/:id':fn_getById,
    'post /product':fn_post,
    'put /product/:id':fn_put,
    'delete /product/:id':fn_delete
}